/* USER CODE BEGIN Header */
/**
 * @brief
 *
 *
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include <main.h>
/* USER CODE BEGIN Includes */
// 舵机参数宏定义（统一管理，便于修改）
#define SERVO_MIN_PULSE 50    // 0.5ms 对应计数值（0°）
#define SERVO_MAX_PULSE 250   // 2.5ms 对应计数值（180°）
#define SERVO_ANGLE_RANGE 180 // 角度范围0-180°
#define PWM_PERIOD 2000       // 定时器周期（20ms）
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim4;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM4_Init(void);

/* USER CODE BEGIN PFP */
void Servo_Control(uint8_t angle, uint8_t direction);               // 基础角度控制
void Servo_Control_Smooth(uint8_t target_angle, uint8_t direction); // 平滑角度控制
void Servo_SetAngle_MethodB(int16_t TarAngle);                      // 舵机控制方法二：步进设置CCR
void Servo_SetAngle_MethodC(int16_t TarAngle);                      // 舵机控制方法三：通过一阶滤波设置CCR
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/**
 * @brief  基础角度控制（参数化映射）
 * @param  angle: 目标角度（0-180°）
 * @param  direction: 方向（0=正转：0°→SERVO_MIN_PULSE；1=反转：0°→SERVO_MAX_PULSE）
 * @retval None
 */
void Servo_Control(uint8_t angle, uint8_t direction)
{
  uint32_t pulse_width;

  // 限制角度范围
  angle = (angle > SERVO_ANGLE_RANGE) ? SERVO_ANGLE_RANGE : angle;

  // 角度→脉宽映射（线性计算）
  if (direction == 0)
  {
    pulse_width = SERVO_MIN_PULSE + (angle * (SERVO_MAX_PULSE - SERVO_MIN_PULSE)) / SERVO_ANGLE_RANGE;
  }
  else
  {
    pulse_width = SERVO_MAX_PULSE - (angle * (SERVO_MAX_PULSE - SERVO_MIN_PULSE)) / SERVO_ANGLE_RANGE;
  }

  // 最终脉宽限制
  pulse_width = (pulse_width < SERVO_MIN_PULSE) ? SERVO_MIN_PULSE : pulse_width;
  pulse_width = (pulse_width > SERVO_MAX_PULSE) ? SERVO_MAX_PULSE : pulse_width;

  __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_3, pulse_width);
}

/**
 * @brief  平滑角度控制（逐步过渡，无滤波冗余）
 * @param  target_angle: 目标角度（0-180°）
 * @param  direction: 方向（同 Servo_Control）
 * @retval None
 */
void Servo_Control_Smooth(uint8_t target_angle, uint8_t direction)
{
  static uint8_t current_angle = 90; // 初始角度设为中点
  uint8_t step = 2;                  // 步长（越小越平滑，建议2-5°）

  // 限制目标角度
  target_angle = (target_angle > SERVO_ANGLE_RANGE) ? SERVO_ANGLE_RANGE : target_angle;

  // 逐步逼近目标角度
  if (current_angle < target_angle)
  {
    current_angle += (current_angle + step > target_angle) ? (target_angle - current_angle) : step;
    Servo_Control(current_angle, direction);
    HAL_Delay(10); // 控制转速（10ms/步）
  }
  else if (current_angle > target_angle)
  {
    current_angle -= (current_angle - step < target_angle) ? (current_angle - target_angle) : step;
    Servo_Control(current_angle, direction);
    HAL_Delay(10);
  }
}

/**
 * @brief  舵机控制方法二：步进设置CCR
 * @param  TarAngle: 目标角度
 * @retval None
 * @note   该方法逐步以5度步进调整到目标角度，控制移动速度
 */
void Servo_SetAngle_MethodB(int16_t TarAngle)
{
  // 该方法使用步进方式逐步到达目标角度，每次移动5度
  static uint8_t NowAngle = 0; // 当前角度
  uint32_t min_pulse = 50;     // 0.5ms对应的计数值 (0度)
  uint32_t max_pulse = 250;    // 2.5ms对应的计数值 (180度)
  uint32_t angle_range = 180;  // 角度范围
  uint32_t pulse_width;

  // 限制目标角度范围在0-180度
  if (TarAngle < 0)
    TarAngle = 0;
  if (TarAngle > 180)
    TarAngle = 180;
  // 循环逐步调整角度
  while (NowAngle != TarAngle)
  {
    if (NowAngle < TarAngle)
    {
      NowAngle += 5; // 增加5度
      if (NowAngle > TarAngle)
        NowAngle = TarAngle; // 防止超过目标角度
    }
    else if (NowAngle > TarAngle)
    {
      NowAngle -= 5; // 减少5度
      if (NowAngle < TarAngle)
        NowAngle = TarAngle; // 防止低于目标角度
    }
    // 使用与Servo_Control相同的线性映射：0度->50, 180度->250
    pulse_width = min_pulse + (NowAngle * (max_pulse - min_pulse)) / angle_range;
    __HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_3, pulse_width);

    // 延时控制步进速度
    HAL_Delay(30); // 每步延时30ms
  }
  // 如果PWM未启动，则启动它
  if ((htim4.Instance->CCER & TIM_CCER_CC3E) == 0)
  {
    HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);
  }
}

/**
 * @brief  舵机控制方法三：通过一阶滤波设置CCR
 * @param  TarAngle: 目标角度（0-180°）
 * @retval None
 * @note   使用一阶滤波逐步平滑调整到目标角度，避免舵机抖动
 */
void Servo_SetAngle_MethodC(int16_t TarAngle)
{
  uint32_t min_pulse = 50;    // 0.5ms对应的计数值 (0度)
  uint32_t max_pulse = 250;   // 2.5ms对应的计数值 (180度)
  uint32_t angle_range = 180; // 角度范围
  uint32_t TarCCR;            // 目标CCR值
  static float SetCCR = 0;    // 当前设置的CCR值
  static float LastCCR = 0;   // 上一次的CCR值

  // 限制目标角度范围在0-180度
  if (TarAngle < 0)
    TarAngle = 0;
  if (TarAngle > 180)
    TarAngle = 180;

  // 计算目标CCR值（线性映射：0度->50, 180度->250）
  TarCCR = min_pulse + (TarAngle * (max_pulse - min_pulse)) / angle_range;

  // 一阶滤波系数（越小越平滑，但响应越慢）
  const float Belta = 0.2;

  // 死区设定，防止舵机抖动
  if (fabs(SetCCR - TarCCR) < 1)
  {
    SetCCR = TarCCR;
  }
  else
  {
    SetCCR = Belta * TarCCR + (1 - Belta) * LastCCR;
  }

  // 更新上一次的CCR值
  LastCCR = SetCCR;

  // 设置PWM占空比
  __HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_3, (uint32_t)SetCCR);

  // 延时控制滤波步进速度
  HAL_Delay(8);
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM4_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);

  // Servo_Control(0, 0);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    // 示例1：直接控制角度，0° -> 180° -> 0°，正转模式
    Servo_Control(0, 0);
    HAL_Delay(1000);
    Servo_Control(180, 0);
    HAL_Delay(1000);
    // 直接控制角度：0° -> 180° -> 0°，正转模式
    Servo_SetAngle_MethodC(0);
    HAL_Delay(1000);
    Servo_SetAngle_MethodC(180);
    HAL_Delay(1000);

    // 示例：逐步将舵机从 0° 移动到 180°，再移动回 0°
    Servo_SetAngle_MethodB(0);   // 缓慢移动到 180°
    HAL_Delay(1000);             // 停留 1 秒
    Servo_SetAngle_MethodB(180); // 缓慢移动回 0°
    HAL_Delay(1000);             // 停留 1 秒

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
   */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = 0;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 40;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
   */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
 * @brief TIM4 Initialization Function
 * @param None
 * @retval None
 */
static void MX_TIM4_Init(void)
{

  /* USER CODE BEGIN TIM4_Init 0 */

  /* USER CODE END TIM4_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};

  /* USER CODE BEGIN TIM4_Init 1 */

  /* USER CODE END TIM4_Init 1 */
  htim4.Instance = TIM4;
  htim4.Init.Prescaler = 800 - 1;
  htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim4.Init.Period = 2000 - 1;
  htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 0;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM4_Init 2 */

  /* USER CODE END TIM4_Init 2 */
  HAL_TIM_MspPostInit(&htim4);
}

/**
 * @brief GPIO Initialization Function
 * @param None
 * @retval None
 */
static void MX_GPIO_Init(void)
{
  /* USER CODE BEGIN MX_GPIO_Init_1 */

  /* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /* USER CODE BEGIN MX_GPIO_Init_2 */

  /* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
